package com.yiqi.liebang.feature.wallet.view;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.T;
import com.suozhang.framework.utils.logger.Logger;
import com.suozhang.framework.widget.PowerfulEditText;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yiqi.liebang.R;
import com.yiqi.liebang.common.alipay.PayResult;
import com.yiqi.liebang.entity.bo.BanlanceBo;
import com.yiqi.liebang.entity.bo.PayBo;
import com.yiqi.liebang.entity.bo.PublicBo;
import com.yiqi.liebang.feature.wallet.contract.WalletContract;
import com.yiqi.liebang.feature.wallet.dependencies.wallet.DaggerWalletComponent;
import com.yiqi.liebang.feature.wallet.dependencies.wallet.WalletPresenterModule;
import com.yiqi.liebang.wxapi.WXPayEntryActivity;

import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

public class RechargeActivity extends BaseActivity implements WalletContract.View {


    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    RechargeDialog mRechargeDialog;


    @BindView(R.id.edt_prize)
    PowerfulEditText mEdtPrize;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_recharge;
    }
    @Inject

    WalletContract.Presenter mPresenter;
    @Override
    protected void initInjector() {
        DaggerWalletComponent.builder().walletPresenterModule(new WalletPresenterModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {
        initToolBar(mToolbar, "充值", true, true);
    }

    @Override
    protected void initData() {

        IntentFilter filter = new IntentFilter(WXPayEntryActivity.action);
        registerReceiver(broadcastReceiver, filter);
    }
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                if (intent.getBooleanExtra("data",false)){
                    finish();
                }
            }
        }

    };


    @OnClick(R.id.btn_recharge_next)
    public void onViewClicked() {
        if (TextUtils.isEmpty(mEdtPrize.getText().toString())) {
            showMsg("请输入有效金额！");
            return;
        }
        double prize = Double.valueOf(mEdtPrize.getText().toString());
        if (prize <= 0) {
            showMsg("请输入有效金额！");
            return;
        }
        mRechargeDialog = new RechargeDialog(this,prize);
        mRechargeDialog.show();
        mRechargeDialog.setListener(new RechargeDialog.MyClickListenerInterface() {
            @Override
            public void doConfirm(int type) {
                mPayType=type;
                mPresenter.userRechagre(type, prize);
            }
        });
    }
    private int mPayType;

    private void toWxPay(PayBo.WechatBo wxPayBo) {
        IWXAPI api = WXAPIFactory.createWXAPI(this, wxPayBo.getAppid());
        api.registerApp(wxPayBo.getAppid());
        PayReq req = new PayReq();
        req.appId = wxPayBo.getAppid();
        req.partnerId = wxPayBo.getPartnerid();
        req.prepayId = wxPayBo.getPrepayid();
        req.nonceStr = wxPayBo.getNoncestr();
        req.timeStamp = wxPayBo.getTimestamp();
        req.packageValue = "Sign=WXPay";
        req.sign = wxPayBo.getSign();
        api.sendReq(req);
    }

    @Override
    public void showSuccess(String error) {

    }

    @Override
    public void showPaySuccess(PayBo classifyBos) {

       try {
           if(classifyBos!=null){
               if (mPayType == 0) {
                   if(classifyBos.getAlipay_url()!=null){
                       toAlipay(classifyBos.getAlipay_url());
                   }

               } else if (mPayType == 1) {
                   if(classifyBos.getWxpay_url()!=null){
                       toWxPay(classifyBos.getWxpay_url());
                   }

               }
           }

       }catch (Exception e){
           e.printStackTrace();
       }
    }

    @Override
    public void userWithdrawSucc(PublicBo entity) {

    }

    @Override
    public void showTransactionListSuccess(List<BanlanceBo.ListData> workBoPageData) {

    }


    @Override
    public void showError(String error) {
        showMsg(error);
    }

    @Override
    public void showTransactionListMoreSuccess(List<BanlanceBo.ListData> msg) {

    }


    @Override
    public void showTransactionListMoreError(String msg) {

    }

    @Override
    public void showTransactionListEmpty() {

    }

    /**
     * 支付宝支付
     */
    private void toAlipay(String msg) {

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(RechargeActivity.this);
                Map<String, String> result = alipay.payV2(msg, true);
                Logger.e("msg-------->", result.toString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    private static final int SDK_PAY_FLAG = 1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        T.showShort("支付成功");
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        T.showShort("支付失败");
                    }
                    break;
                }
                default:
                    break;
            }
        }

    };
}
